package com.julyup.core.service;

import com.julyup.core.constant.AreaEnum;
import com.julyup.core.entity.Company;
import com.julyup.core.util.HttpUtils;
import com.julyup.core.util.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 慧聪网信息爬取
 *
 * @Author: zhenzhong.wang@honeywell.com
 * @Date: 2019/4/18 4:23 PM
 */
@Service
@Slf4j
public class HCSearchService {

  private String searchUrl = "https://s.hc360.com/company/search.html";

  private int psize = 100;
  private int pnums = 100;
  private AreaEnum area = AreaEnum.SHANGHAI;

  @Autowired
  CompanyService companyService;

  public void start() {
    ThreadUtils.getPool().execute(() -> {
      for (int i = 1; i <= pnums; i++) {
        crawling(area, psize, i);
      }
    });
  }

  public void crawling(AreaEnum area, int psize, int pnum) {

    log.info("慧聪网 - 第{}页解析开始", pnum);

    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("kwd", area.getArea());
    paramMap.put("psize", psize);
    paramMap.put("pnum", pnum);

    String responseStr = HttpUtils.sendGet(searchUrl, null, paramMap);
    Document doc = Jsoup.parse(responseStr);
    Elements elements = doc.select("#filterform + div").select("div.col");

    ArrayList<Company> companyList = new ArrayList<>();

    for (Element ele : elements) {
      Company company = new Company();

      // 清洗数据
      company.setCompanyName(ele.select("h3 a").first().attr("title"));

      // 验证数据库中是否已存在
      if (companyService.ifPresentInDB(company.getCompanyName())) {
        continue;
      }

      company.setLocation(splitByColon(ele.select("dt > a").last().text()));
      if (ele.select("dt.til h3 + a").size() > 0) {
        company.setOnlineTime(ele.select("dt.til h3 + a").first().text().replace("买卖通 ", ""));
      }
      company.setSite(ele.select("dt.til h3 a").first().attr("href"));

      for (Element a : ele.select("dd > a")) {
        String aText = a.text();
        if (aText.contains("经营模式")) {
          company.setMode(splitByColon(aText));
        } else if (aText.contains("主营行业")) {
          company.setIndustry(splitByColon(aText));
        } else if (aText.contains("成立时间")) {
          company.setRegTime(splitByColon(aText));
        }
      }

      try {
        reflectDetailToCompany(company);
      } catch (Exception e) {
        log.error("{} 信息解析异常！", company.getCompanyName());
//        e.printStackTrace();
      }

      company.setOrigin("慧聪网");
      companyList.add(company);
    }

    companyService.save(companyList);
//    ExportUtils.exportCompanyToExcel(companyList);
    log.info("慧聪网 - 第{}页解析完成，数量：{}", pnum, companyList.size());
  }

  /**
   * 映射company的详细信息
   *
   * @param company
   */
  public void reflectDetailToCompany(Company company) {
    if (StringUtils.isEmpty(company.getSite())) {
      return;
    }

    String companyDetailUrl = company.getSite() + "/shop/company.html";

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    String responseStr = HttpUtils.sendGet(companyDetailUrl);
    Document doc = Jsoup.parse(responseStr);
    Element contactPage = doc.select("div.ContactPage").first();

    // 解析联系方式
    Elements eles = contactPage.select("div.con3Rig");
    company.setContactPerson(eles.get(0).select("span").first().text());

    for (Element e : eles) {
      // 固定电话
      if ("telephone".equals(e.attr("node-name"))) {
        company.setTelephone(e.text());
      } else if ("mp".equals(e.attr("node-name"))) {
        company.setCellphone(e.text());
      } else if ("otherTelephone".equals(e.attr("node-name"))) {
        company.setOtherContacts(e.text());
      }
    }

  }

  /**
   * 根据冒号分割字符并去冒号后的字符串
   *
   * @param source
   * @return
   */
  public String splitByColon(String source) {
    if (source == null) {
      return null;
    }
    String target;
    try {
      target = source.split("：")[1];
    } catch (ArrayIndexOutOfBoundsException e) {
      return null;
    }
    return target;
  }
}
